﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Seven.Tools.Helper
{
    public static class EnumHelper
    {
        /// <summary>
        /// 获取枚举SelectListItem集合，以text,text格式返回 
        /// </summary>
        /// <typeparam name="TEnum">枚举类型</typeparam>
        /// <param name="enumType">枚举类型</param>
        /// <returns></returns>
        public static IEnumerable<SelectListItem> GetEnumItems<TEnum>(Type enumType)
        {
            IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();

            IEnumerable<SelectListItem> items =
                values.Select(value => new SelectListItem
                {
                    Text = value.ToString(),
                    Value = value.ToString()
                });
            return items;
        }

        /// <summary>
        /// 获取枚举SelectListItem集合，以value text格式返回
        /// </summary>
        /// <typeparam name="TEnum">枚举类型</typeparam>
        /// <param name="enumType">枚举类型</param>
        /// <returns></returns>
        public static List<SelectListItem> GetListItems<TEnum>(Type enumType)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            foreach (int key in Enum.GetValues(enumType))
            {
                items.Add(new SelectListItem() { Value = key.ToString(), Text = Enum.GetName(enumType, key) });
            }

            return items;
        }

        /// <summary>
        /// 获取text在枚举内的值
        /// </summary>
        /// <typeparam name="TEnum">枚举类型</typeparam>
        /// <param name="enumText">枚举的text值</param>
        /// <param name="enumType">枚举类型</param>
        /// <returns></returns>
        public static TEnum GetKey<TEnum>(string enumText, Type enumType)
        {
            return (TEnum)Enum.Parse(enumType, enumText);
        }
    }
}
